package 算法.二分查找;

import java.util.Scanner;

public class text1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数：");
        int num = sc.nextInt();
        //数组必须是有序数组
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        int i = compareText(arr, num);
        System.out.println(i);
    }

    //自定义二分查找方法
    private static int compareText(int[] arr, int num) {
        //定义最大和最小索引
        int min = 0;
        int max = arr.length-1;

        while (true){
            if (max < min) {
                //数据不存在
                return -1;
            }

            //定义中间索引
            int mid = (max + min) / 2;

            if (arr[mid] < num){
                min = mid + 1;
            }else if (arr[mid] > num){
                max = mid - 1;
            }else {
                return mid;
            }
        }
    }
}
